// next-reviews-me/lib/reviews.js
// import { readdir, readFile } from "node:fs/promises"; // 服务端可以访问node
// import matter from "gray-matter";
import 'server-only' // 只从服务端发请求，防止客户端向CMS发请求
import {marked} from "marked";
import qs from 'qs'

// const CMS_URL = 'http://localhost:1337'
const CMS_URL = process.env.CMS_URL
export const CACHE_TAG_REVIEWS = 'reviews'

export async function getFeaturedReview() {
    const reviews = await getReviews()
    return reviews[0]
}

export async function getReview(slug) {
    const {data} = await fetchReviews({
        filters: {slug: {$eq: slug}},
        fields: ['slug', 'title', 'subtitle', 'publishedAt', 'body'],
        populate: {image: {fields: ['url']}},
        pagination: {pageSize: 1, withCount: false}
    })
    if (data.length === 0) {
        return null
    }
    const item = data[0]
    return {
        ...toReview(item),
        body: marked(item.attributes.body)
    }
}

export async function getReviews(pageSize, page) {
    const {data, meta} = await fetchReviews({
        fields: ['slug', 'title', 'subtitle', 'publishedAt'],
        populate: {image: {fields: ['url']}},
        sort: ['publishedAt:desc'], // 按发布时间排序
        pagination: {pageSize, page}
    })
    return {
        pageCount: meta.pagination.pageCount,
        reviews: data.map(toReview)
    }
}

export async function getSlugs() {
    const {data} = await fetchReviews({
        fields: ['slug'],
        sort: ['publishedAt:desc'], // 按发布时间排序
        pagination: {pageSize: 100}
    })
    return data.map((item) => item.attributes.slug)
}

export async function searchReviews(query) {
    const {data} = await fetchReviews({
        filters: {title: {$containsi: query}},
        fields: ['slug', 'title'],
        sort: ['title'],
        pagination: {pageSize: 5}
    })
    return data.map(({attributes}) => ({
        slug: attributes.slug,
        title: attributes.title,
    }))
}

async function fetchReviews(parameters) {
    const url = `${CMS_URL}/api/reviews?` +
        qs.stringify(parameters, {encodeValuesOnly: true})
    const response = await fetch(url, {
        // 禁用fetch的缓存，next build时会根据是否需要动态数据来生成静态或动态页面
        // 效果和force-dynamic类似
        // cache: 'no-store'
        next: {
            // revalidate: 30, // seconds
            tags: [CACHE_TAG_REVIEWS]
        }
    })
    if (!response.ok) {
        throw new Error(`CMS returned ${response.status} for ${url}`)
    }
    return await response.json()
}

function toReview(item) {
    const {attributes} = item
    return {
        slug: attributes.slug,
        title: attributes.title,
        date: attributes.publishedAt.slice(0, 'yyyy-mm-dd'.length),
        subtitle: attributes.subtitle,
        image: CMS_URL + attributes.image.data.attributes.url
    }
}